package genesis.familytree.server.common.code.builder;

import genesis.familytree.server.common.code.*;
import genesis.familytree.server.common.exception.ExpressionException;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 */
public class HiddenExprBuilder extends AbstractDataTypeBuilder implements DataTypeBuilder, DataNameBuilder {


    @Override
    public String build(String name, String format, Params params) throws ExpressionException {

        Object obj = getValue(name, params);
        if (null == obj) {
            return null;
        }
        String value = obj.toString();

        Pattern p = Pattern.compile(format);

        Matcher m = p.matcher(value);
        StringBuilder sb = new StringBuilder();

        int start = 0;
        if (m.matches()) {
            for (int i = 1; i <= m.groupCount(); i++) {
                int end = m.start(i);
                String str = m.group(i);

                sb.append(value.substring(start, end));
                sb.append(StringUtils.leftPad("", str.length(), "*"));
                start = m.end(i);
            }

            sb.append(value.substring(start));

            return sb.toString();
        }

        return null;
    }

    @Override
    public Attribute build(Expression expr, int startIndex, int endIndex, String expression) {
        if (!expression.contains(":")) {
            return null;
        }

        String[] attrs = expression.split(":", 3);
        if (attrs.length != 3) {
            return null;
        }

        String name = attrs[0];
        String dataType = attrs[1];
        if (!"hidden".equals(dataType)) {
            return null;
        }
        String format = attrs[2];

        return new Attribute(expr, startIndex, endIndex, name, dataType, format);
    }
}
